import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
import { Table, Modal } from 'antd';

import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址

import { formatCourseRecordData } from "./formatutils.js"
import AdminNavBar from './nav/AdminNavBar.js'
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';


const Admin_getStudentInfoList = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [StudentInfoList, setStudentInfoList] = useState([]);//所有学生信息列表
    const [hideParagraph, setHideParagraph] = useState(true);
    const [record, setrecord] = useState();
    const [IsList, setIsList] = useState(false);//控制是否显示列表
    const [categoryFilter, setCategoryFilter] = useState('');//用于通过分类查询

    const columns = [
        {
            title: '真实姓名',
            dataIndex: 'realName',
            key: 'realName',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '身份证号',
            dataIndex: 'idNumber',
            key: 'idNumber',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '学号',
            dataIndex: 'studentIDNumber',
            key: 'studentIDNumber',
            render: (text) => {
                const newText = text; // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '班级',
            dataIndex: 'classNumber',
            key: 'classNumber',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '学历',
            dataIndex: 'educationalLevel',
            key: 'educationalLevel',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '年级',
            dataIndex: 'gradeLevel',
            key: 'gradeLevel',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '积分',
            dataIndex: 'nowPoint',
            key: 'nowPoint',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '学分',
            dataIndex: 'nowCredit',
            key: 'nowCredit',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            render: (text) => {
                const newText = text; // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText == true ? '男' : '女'}</span>;
            },
        },
        {
            title: '电话号码',
            dataIndex: 'phone',
            key: 'phone',
            render: (text) => {
                const newText = text; // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: 'password',
            render: (text) => {
                const newText = text; // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
    ];
    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);

                    // 自动获取学生信息列表
                    await Admin_getStudentInfoList(userListInstance, web3Instance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    // // 自动加载方法
    // useEffect(() => {
    //     if (contractCourseRecordList) {
    //         Admin_getStudentInfoList()
    //     }
    // }, [contractCourseRecordList])
    //获取所有学生信息
    const Admin_getStudentInfoList = async (userListInstance, web3Instance) => {
        if (userListInstance) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3Instance.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);

                // 调用智能合约的某个函数
                await userListInstance.methods.getUserInfoList().call({ from: fromAddress }).then((result) => {
                    setStudentInfoList(result)
                    setIsList(true);//让列表显示出来

                })
            } catch (error) {
                console.error(error);
                alert("查询失败")
            }
        }
    };

    const handleFilterActivity = async () => {
        if (contractCourseRecordList) {
            try {
                const filteredActivityList = StudentInfoList.filter((activity) => activity.studentIDNumber === categoryFilter);//设置通过类别查询
                setStudentInfoList(filteredActivityList);

                setIsList(true);

            } catch (error) {
                console.error(error);
            }
        }
    };
    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div className="page-wrapper" style={{
                    backgroundColor: '#FFFFFF'
                }}>
                    <div className="main-container">
                        <AdminNavBar address={address}></AdminNavBar>

                        <div className="app-container">
                            <Head></Head>

                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">
                                                <div className="foreground-component">
                                                    <div className="container">
                                                        <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                            data-bs-theme="light"
                                                            style={{
                                                                backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                                            }}
                                                        >
                                                            <h1>获取学生信息列表</h1>
                                                            <div className="d-flex justify-content-end mt-3">
                                                                <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                                                    <input
                                                                        type="text"
                                                                        className="form-control"
                                                                        placeholder="输入学号查询"
                                                                        aria-label="学号查询"
                                                                        aria-describedby="basic-addon2"
                                                                        value={categoryFilter}
                                                                        onChange={(e) => setCategoryFilter(e.target.value)}
                                                                    />
                                                                    <div className="input-group-append">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={handleFilterActivity}>查询</button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            {IsList ? (
                                                                <Table
                                                                    dataSource={StudentInfoList}
                                                                    columns={columns} // 确保你已经定义了columns
                                                                    pagination={{
                                                                        pageSize: 2,
                                                                        showTotal: false, // 隐藏总页数
                                                                        showSizeChanger: false, // 隐藏页面大小选择器
                                                                        itemRender: (current, type, originalElement) => (
                                                                            <span style={{ color: 'black' }}>
                                                                                {current}
                                                                            </span>
                                                                        ),
                                                                    }}
                                                                />
                                                            ) : (
                                                                <div>No activity information available.</div>
                                                            )}
                                                            {/* <div className="mb-3 mt-4">
                                            <button className="btn btn-primary btn-lg d-block w-100" onClick={Admin_getStudentInfoList}>查询用户列表信息</button>
                                        </div> */}
                                                        </div>
                                                    </div>
                                                </div>
                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div>
    );
}

export default Admin_getStudentInfoList;